#include "ftpclientmainwindow.h"
#include "ui_ftpclientmainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QMenu>
#include <QAction>
#include <QFileInfo>
#include <QDir>
#include <QDateTime>
#include "ftpclient.h"
#include <QSettings>


qint64 FileSizeSortProxyModel::getActualFileSize(const QModelIndex& index) const {
    if (m_isRemote && m_fileSizeMap) {
        // 对于远程文件，从文件大小映射表中获取
        QString fileName = sourceModel()->data(sourceModel()->index(index.row(), 0)).toString();
        if (m_fileSizeMap->contains(fileName)) {
            return m_fileSizeMap->value(fileName);
        }
    }
    else if (!m_isRemote && m_localFileTable) {
        // 对于本地文件，通过QFileInfo重新获取大小
        QString fileName = sourceModel()->data(sourceModel()->index(index.row(), 0)).toString();
        QString currentPath = m_currentLocalPath; // 需要在FtpClientMainWindow中添加这个成员
        QString fullPath = QDir(currentPath).absoluteFilePath(fileName);
        QFileInfo fileInfo(fullPath);
        if (fileInfo.exists()) {
            return fileInfo.size();
        }
    }

    // 如果无法获取实际大小，尝试从显示文本解析
    QString sizeText = sourceModel()->data(index).toString();
    return parseFileSize(sizeText);
}

qint64 FileSizeSortProxyModel::parseFileSize(const QString& sizeText) const {
    // 解析类似 "1.23 MB" 这样的字符串
    QString cleanText = sizeText.trimmed();
    if (cleanText.isEmpty()) return 0;

    QStringList parts = cleanText.split(' ');
    if (parts.size() < 1) return 0;

    bool ok;
    double size = parts[0].toDouble(&ok);
    if (!ok) return 0;

    // 根据单位转换为字节
    if (parts.size() >= 2) {
        QString unit = parts[1].toUpper();
        if (unit == "KB") size *= 1024;
        else if (unit == "MB") size *= 1024 * 1024;
        else if (unit == "GB") size *= 1024 * 1024 * 1024;
        // 默认为字节
    }

    return static_cast<qint64>(size);
}

// 在构造函数中添加初始化代码
FtpClientMainWindow::FtpClientMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::FtpClientMainWindow),
    m_ftpClient(new FtpClient(this)),
    m_port(21)
{
    ui->setupUi(this);
    
    // 初始化排序代理
    m_localFileSortProxy = new FileSizeSortProxyModel(this);
    m_remoteFileSortProxy = new FileSizeSortProxyModel(this);
    
    // 配置远程文件排序代理，使用现有的文件大小映射表
    m_remoteFileSortProxy->setFileSizeMap(&m_fileSizeMap, true);
    
    // 配置本地文件排序代理
    m_localFileSortProxy->setLocalFileTable(ui->localFileTableWidget);
    
    // 初始化当前本地路径
    m_currentLocalPath = QDir::currentPath();
    
    // 初始化菜单
    setupMenus();
    
    // 设置信号槽连接
    setupConnections();
    
    // 初始加载本地文件列表
    refreshLocalFileList(ui->localPathLineEdit->text());
    
    // 初始化按钮状态：连接前状态
    ui->connectButton->setText("连接");
    ui->connectButton->setEnabled(true);
}

FtpClientMainWindow::~FtpClientMainWindow()
{
    if (!m_iniFile.isEmpty()) {
        saveSettings(m_iniFile, m_groupName);
    }
    m_ftpClient->disconnect();
    delete m_ftpClient;
    delete ui;
}

void FtpClientMainWindow::setupMenus()
{
    // 远程文件右键菜单
    m_remoteContextMenu = new QMenu(this);
    m_downloadAction = new QAction("下载", this);
    m_deleteAction = new QAction("删除", this);
    m_refreshRemoteAction = new QAction("刷新", this);
    m_remoteContextMenu->addAction(m_downloadAction);
    m_remoteContextMenu->addAction(m_deleteAction);
    m_remoteContextMenu->addAction(m_refreshRemoteAction);
    
    // 本地文件右键菜单
    m_localContextMenu = new QMenu(this);
    m_uploadAction = new QAction("上传", this);
    m_deleteLocalAction = new QAction("删除", this); // 本地文件删除动作
    m_refreshLocalAction = new QAction("刷新", this); // 本地文件刷新动作
    
    m_localContextMenu->addAction(m_uploadAction);
    m_localContextMenu->addAction(m_deleteLocalAction); // 添加删除动作到菜单
    m_localContextMenu->addAction(m_refreshLocalAction); // 添加刷新动作到菜单
    
    // 设置表格上下文菜单策略
    ui->remoteFileTableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->localFileTableWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    // 初始化本地文件列表表格
    // 隐藏行号
    ui->localFileTableWidget->verticalHeader()->setVisible(false);
    // 设置表头可调整宽度
    ui->localFileTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    // 设置表格不可编辑
    ui->localFileTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // 启用排序功能 
    // ui->localFileTableWidget->setSortingEnabled(true);

    // 初始化远程文件列表表格
    // 隐藏行号
    ui->remoteFileTableWidget->verticalHeader()->setVisible(false);
    // 设置表头可调整宽度
    ui->remoteFileTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    // 设置表格不可编辑
    ui->remoteFileTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // 启用排序功能
    // ui->remoteFileTableWidget->setSortingEnabled(true);
       // 设置表格不可编辑
    ui->remoteFileTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    // 设置表格列头
    ui->remoteFileTableWidget->setColumnCount(4);
    QStringList headers;
    headers << "文件名" << "类型" << "大小" << "创建时间";
    ui->remoteFileTableWidget->setHorizontalHeaderLabels(headers);

    // 设置表格列头
    ui->localFileTableWidget->setColumnCount(4);
    //QStringList headers;
    //headers << "文件名" << "类型" << "大小" << "创建时间";
    ui->localFileTableWidget->setHorizontalHeaderLabels(headers);

    ui->localFileTableWidget->horizontalHeader()->setSortIndicatorShown(true);
    ui->remoteFileTableWidget->horizontalHeader()->setSortIndicatorShown(true);

    for (int i = 0;i < FILE_LIST_COLUMNS;i++) {
        localColOrder[i] = Qt::AscendingOrder;
        remoteColOrder[i] = Qt::AscendingOrder;
    }
}

void FtpClientMainWindow::setupConnections()
{
    // UI按钮连接
    connect(ui->connectButton, &QPushButton::clicked, this, &FtpClientMainWindow::onConnectButtonClicked);
    connect(ui->listFilesButton, &QPushButton::clicked, this, &FtpClientMainWindow::onListButtonClicked);
    connect(ui->downloadButton, &QPushButton::clicked, this, &FtpClientMainWindow::onDownloadButtonClicked);
    connect(ui->uploadButton, &QPushButton::clicked, this, &FtpClientMainWindow::onUploadButtonClicked);
    connect(ui->selectPathButton, &QPushButton::clicked, this, &FtpClientMainWindow::onSelectLocalPathButtonClicked);
    
    // 右键菜单连接
    connect(ui->remoteFileTableWidget, &QTableWidget::customContextMenuRequested,
            this, &FtpClientMainWindow::onRemoteFileTableContextMenuRequested);
    connect(ui->localFileTableWidget, &QTableWidget::customContextMenuRequested,
            this, &FtpClientMainWindow::onLocalFileTableContextMenuRequested);
    
    connect(m_downloadAction, &QAction::triggered, this, &FtpClientMainWindow::onDownloadActionTriggered);
    connect(m_uploadAction, &QAction::triggered, this, &FtpClientMainWindow::onUploadActionTriggered);
    connect(m_deleteAction, &QAction::triggered, this, &FtpClientMainWindow::onDeleteActionTriggered);
    connect(m_refreshRemoteAction, &QAction::triggered, this, &FtpClientMainWindow::onRefreshRemoteActionTriggered);
    connect(m_deleteLocalAction, &QAction::triggered, this, &FtpClientMainWindow::onDeleteLocalActionTriggered); // 连接删除动作
    connect(m_refreshLocalAction, &QAction::triggered, this, &FtpClientMainWindow::onRefreshLocalActionTriggered); //连接刷新动作
    
  
    // 连接远程文件列表的双击事件
    connect(ui->remoteFileTableWidget, &QTableWidget::cellDoubleClicked, 
            this, &FtpClientMainWindow::onRemoteFileCellDoubleClicked);
    
    // 连接表头点击信号，实现双击排序
    connect(ui->localFileTableWidget->horizontalHeader(), &QHeaderView::sectionDoubleClicked, 
            this, &FtpClientMainWindow::onLocalTableHeaderDoubleClicked);
    
    connect(ui->remoteFileTableWidget->horizontalHeader(), &QHeaderView::sectionDoubleClicked, 
            this, &FtpClientMainWindow::onRemoteTableHeaderDoubleClicked);
}

void FtpClientMainWindow::refreshLocalFileList(const QString &path)
{
    // 保存当前路径
    m_currentLocalPath = path;
    
    // 清空表格
    ui->localFileTableWidget->clearContents();
    ui->localFileTableWidget->setRowCount(0);
    
   
    // 获取本地文件列表
    QDir dir(path);
    if (!dir.exists()) {
        return;
    }

    // 获取目录中的所有文件和子目录
    QFileInfoList fileList = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot,
        QDir::DirsFirst | QDir::Name);
    
    // 填充表格
    int row = 0;
    foreach (const QFileInfo &fileInfo, fileList) {
        ui->localFileTableWidget->insertRow(row);
        
        // 文件名
        QTableWidgetItem *nameItem = new QTableWidgetItem(fileInfo.fileName());
        ui->localFileTableWidget->setItem(row, 0, nameItem);
        
        // 文件类型
        QString type = fileInfo.isDir() ? "文件夹" : "文件";
        QTableWidgetItem *typeItem = new QTableWidgetItem(type);
        ui->localFileTableWidget->setItem(row, 1, typeItem);
        
        // 文件大小
        QString size;
        if (fileInfo.isFile()) {
            qint64 bytes = fileInfo.size();
            if (bytes < 1024) {
                size = QString("%1 B").arg(bytes);
            } else if (bytes < 1024 * 1024) {
                size = QString("%1 KB").arg(bytes / 1024.0, 0, 'f', 2);
            } else {
                size = QString("%1 MB").arg(bytes / (1024.0 * 1024.0), 0, 'f', 2);
            }
        }
        QTableWidgetItem *sizeItem = new QTableWidgetItem(size);
        ui->localFileTableWidget->setItem(row, 2, sizeItem);
        
        // 创建时间
        QTableWidgetItem *timeItem = new QTableWidgetItem(fileInfo.created().toString("yyyy-MM-dd hh:mm:ss"));
        ui->localFileTableWidget->setItem(row, 3, timeItem);
        
        row++;
    }
}

// UI交互相关槽函数
void FtpClientMainWindow::onConnectButtonClicked()
{
    // 根据按钮文本执行不同操作
    if (ui->connectButton->text() == "连接") {
        // 执行连接操作
        QString host = ui->serverAddressLineEdit->text();
        QString username = ui->usernameLineEdit->text();
        QString password = ui->passwordLineEdit->text();
        
        if (host.isEmpty() || username.isEmpty()) {
            QMessageBox::warning(this, "警告", "请填写服务器地址和用户名");
            return;
        }
        
        ui->statusInfoLabel->setText("正在连接服务器...");
        ui->connectionInfoTextEdit->append("正在连接到服务器: " + host);
        
        // 异步连接
        m_ftpClient->connectToServer(host, username, password, m_port);
    } else {
        // 执行断开连接操作
        ui->statusInfoLabel->setText("正在断开连接...");
        m_ftpClient->disconnectFromServer();
        ui->connectButton->setText("连接");
    }
}

void FtpClientMainWindow::onDisconnectButtonClicked()
{
    ui->statusInfoLabel->setText("正在断开连接...");
    m_ftpClient->disconnectFromServer();
}

void FtpClientMainWindow::onListButtonClicked()
{
    ui->statusInfoLabel->setText("正在获取文件列表...");
    ui->connectionInfoTextEdit->append("正在获取远程文件列表...");
    
    ui->remoteFileTableWidget->clearContents();
    ui->remoteFileTableWidget->setRowCount(0);
    // 获取远程文件列表
    m_ftpClient->listFiles();
}

void FtpClientMainWindow::onDownloadButtonClicked()
{
    // 如果文件名输入框为空，则使用选中的文件名
    if (ui->fileNameLineEdit->text().isEmpty()) {
        // 获取选中的远程文件
        int row = ui->remoteFileTableWidget->currentRow();
        if (row < 0) {
            QMessageBox::warning(this, "警告", "请先选择要下载的文件");
            return;
        }

        QString fileName = ui->remoteFileTableWidget->item(row, 0)->text();
        ui->fileNameLineEdit->setText(fileName);
    }
    m_currentRemoteFile = ui->fileNameLineEdit->text();
    onDownloadActionTriggered();
}

void FtpClientMainWindow::onUploadButtonClicked()
{
    // 获取选中的本地文件
    int row = ui->localFileTableWidget->currentRow();
    if (row < 0) {
        QMessageBox::warning(this, "警告", "请先选择要上传的文件");
        return;
    }
    
    QString fileName = ui->localFileTableWidget->item(row, 0)->text();
    QString filePath = QDir(ui->localPathLineEdit->text()).absoluteFilePath(fileName);
    
    // 开始上传
    ui->statusInfoLabel->setText("正在上传文件...");
    ui->fileTransferProgressBar->setVisible(true);
    ui->fileTransferProgressBar->setValue(0);
    
    m_ftpClient->uploadFile(filePath);
}

void FtpClientMainWindow::onSelectLocalPathButtonClicked()
{
    QString path = QFileDialog::getExistingDirectory(this, "选择本地路径", ui->localPathLineEdit->text());
    if (!path.isEmpty()) {
        ui->localPathLineEdit->setText(path);
        refreshLocalFileList(path);
    }
}

// 本地文件相关槽函数
void FtpClientMainWindow::onLocalFileTableContextMenuRequested(const QPoint &pos)
{
    QTableWidgetItem *item = ui->localFileTableWidget->itemAt(pos);
    if (item) {
        // 保存当前选中的本地文件
        int row = item->row();
        QTableWidgetItem *nameItem = ui->localFileTableWidget->item(row, 0);
        if (nameItem) {
            QString fileName = nameItem->text();
            QString currentPath = ui->localPathLineEdit->text();
            m_currentLocalFile = QDir(currentPath).absoluteFilePath(fileName);
            // 显示右键菜单
            m_localContextMenu->exec(ui->localFileTableWidget->viewport()->mapToGlobal(pos));
        }
    }
}

// 处理本地文件删除的槽函数
void FtpClientMainWindow::onDeleteLocalActionTriggered()
{
    // 显示确认对话框
    QMessageBox::StandardButton reply;
    reply = QMessageBox::warning(this, "确认删除", 
                                 QString("确定要删除文件 '%1' 吗？此操作不可撤销。").arg(m_currentLocalFile),
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        QFileInfo fileInfo(m_currentLocalFile);
        bool success = false;
        
        // 判断是文件还是目录
        if (fileInfo.isDir()) {
            // 删除目录
            QDir dir(m_currentLocalFile);
            success = dir.removeRecursively();
        } else {
            // 删除文件
            success = QFile::remove(m_currentLocalFile);
        }
        
        // 显示操作结果
        if (success) {
            ui->statusInfoLabel->setText("删除成功");
            // 刷新文件列表
            refreshLocalFileList(ui->localPathLineEdit->text());
        } else {
            ui->statusInfoLabel->setText("删除失败");
            QMessageBox::critical(this, "删除失败", 
                                 QString("无法删除文件 '%1'").arg(m_currentLocalFile));
        }
    }
}

// 处理本地文件刷新的槽函数
void FtpClientMainWindow::onRefreshLocalActionTriggered()
{
    // 刷新当前路径的文件列表
    ui->statusInfoLabel->setText("刷新本地文件列表...");
    refreshLocalFileList(ui->localPathLineEdit->text());
    ui->statusInfoLabel->setText("刷新完成");
}

// 远程文件相关槽函数
void FtpClientMainWindow::onRemoteFileTableContextMenuRequested(const QPoint &pos)
{
    // 获取右键点击的单元格所在的行
    int row = ui->remoteFileTableWidget->rowAt(pos.y());
    int column = ui->remoteFileTableWidget->columnAt(pos.x());

    // 只有当点击在有效行范围内（且列也有效）时才处理
    if (row < 0 || row >= ui->remoteFileTableWidget->rowCount() || column < 0) {
        return; // 点击在空白区域，不显示菜单
    }

    // 获取文件名和类型
    QTableWidgetItem* nameItem = ui->remoteFileTableWidget->item(row, 0);
    QTableWidgetItem* typeItem = ui->remoteFileTableWidget->item(row, 1);

    if (!nameItem || !typeItem) return;

    // 只有当点击的是文件类型时才显示右键菜单
    if (typeItem->text() == "文件") {
        // 保存当前右键点击的文件名
        m_currentRemoteFile = nameItem->text();

        // 显示右键菜单
        m_remoteContextMenu->exec(ui->remoteFileTableWidget->mapToGlobal(pos));
    }
}

void FtpClientMainWindow::onDownloadActionTriggered()
{
    // 执行下载操作
    if (!m_currentRemoteFile.isEmpty()) {
        QString localPath = ui->localPathLineEdit->text();
        if (localPath.isEmpty()) {
            localPath = QDir::currentPath();
        }
        
        QString localFilePath = localPath + QDir::separator() + m_currentRemoteFile;
        
        ui->statusInfoLabel->setText("正在下载文件...");
        ui->fileTransferProgressBar->setVisible(true);
        ui->fileTransferProgressBar->setValue(0);

        qint64 filesize = 0;
        if (m_fileSizeMap.contains(m_currentRemoteFile)) {
            filesize = m_fileSizeMap[m_currentRemoteFile];
        }
        
        m_ftpClient->downloadFile(m_currentRemoteFile, localFilePath, filesize);
    }
}

void FtpClientMainWindow::onUploadActionTriggered()
{      
    // 检查是否已连接到服务器
    if (!m_ftpClient->isConnected()) {
        QMessageBox::warning(this, "警告", "请先连接到FTP服务器");
        return;
    }

    // 检查文件是否存在
    QFileInfo fileInfo(m_currentLocalFile);
    if (!fileInfo.exists() || !fileInfo.isFile()) {
        QMessageBox::warning(this, "警告", "文件不存在或不是有效的文件");
        return;
    }

    // 开始上传
    ui->statusInfoLabel->setText("正在上传文件...");
    ui->fileTransferProgressBar->setVisible(true);
    ui->fileTransferProgressBar->setValue(0);
    m_ftpClient->uploadFile(m_currentLocalFile);
}

void FtpClientMainWindow::onDeleteActionTriggered()
{
    // 确认删除
    if (!m_currentRemoteFile.isEmpty()) {
        if (QMessageBox::question(this, "确认删除", "确定要删除文件 " + m_currentRemoteFile + " 吗？") == QMessageBox::Yes) {
            ui->statusInfoLabel->setText("正在删除文件...");
            m_ftpClient->deleteFile(m_currentRemoteFile);
        }
    }
}

void FtpClientMainWindow::onRefreshRemoteActionTriggered()
{
    onListButtonClicked();
}

// FTP客户端信号处理槽函数
void FtpClientMainWindow::onFtpConnected(bool success, const QString &message)
{
    if (success) {
        ui->statusInfoLabel->setText("已连接到服务器");
        ui->connectionInfoTextEdit->append("连接成功");
        // 连接成功后更新按钮状态
        ui->connectButton->setText("断开");
        ui->connectButton->setEnabled(true); // 启用按钮，点击时会执行断开操作
        ui->listFilesButton->setEnabled(true);
        ui->downloadButton->setEnabled(true);
        ui->uploadButton->setEnabled(true);
    } else {
        ui->statusInfoLabel->setText("连接失败");
        ui->connectionInfoTextEdit->append("连接失败: " + message);
        // 连接失败时保持连接按钮状态
        ui->connectButton->setText("连接");
        ui->connectButton->setEnabled(true);
    }
}

void FtpClientMainWindow::onFtpDisconnected()
{
    ui->statusInfoLabel->setText("已断开连接");
    ui->connectionInfoTextEdit->append("已断开与服务器的连接");
    
    // 重置UI状态
    ui->connectButton->setText("连接");
    ui->connectButton->setEnabled(true);
    ui->listFilesButton->setEnabled(false);
    ui->downloadButton->setEnabled(false);
    ui->uploadButton->setEnabled(false);
    
    // 清空远程文件列表
    ui->remoteFileTableWidget->clearContents();
    ui->remoteFileTableWidget->setRowCount(0);
}

void FtpClientMainWindow::onFileListReceived(bool success, const QList<QStringList>& fileList, const QString& message)
{
    if (success) {
        ui->statusInfoLabel->setText("获取文件列表成功");
        ui->connectionInfoTextEdit->append("成功获取远程文件列表");
        

        // 添加到表格 - 调整顺序：先文件名，再类型
        int row = ui->remoteFileTableWidget->rowCount();

        foreach (const QStringList &fileInfo, fileList) {
            ui->remoteFileTableWidget->insertRow(row);
            
            // 文件名
            QTableWidgetItem* nameItem = new QTableWidgetItem(fileInfo[0]);
            ui->remoteFileTableWidget->setItem(row, 0, nameItem);
            
            // 文件类型
            QString type = fileInfo[1];
            QTableWidgetItem *typeItem = new QTableWidgetItem(type);
            ui->remoteFileTableWidget->setItem(row, 1, typeItem);
            
            // 文件大小
            QString size;
            if (type=="文件") {
                qint64 bytes = fileInfo[2].toULongLong();
                m_fileSizeMap[fileInfo[0]] = bytes;
                if (bytes < 1024) {
                    size = QString("%1 B").arg(bytes);
                } else if (bytes < 1024 * 1024) {
                    size = QString("%1 KB").arg(bytes / 1024.0, 0, 'f', 2);
                } else {
                    size = QString("%1 MB").arg(bytes / (1024.0 * 1024.0), 0, 'f', 2);
                }
            }
            QTableWidgetItem *sizeItem = new QTableWidgetItem(size);
            ui->remoteFileTableWidget->setItem(row, 2, sizeItem);
            
            // 创建时间
            QTableWidgetItem* timeItem = new QTableWidgetItem(fileInfo[3]);
            ui->remoteFileTableWidget->setItem(row, 3, timeItem);
            
            row++;
        }
        
        // 调整列宽
        //ui->remoteFileTableWidget->resizeColumnsToContents();
    } else {
        ui->statusInfoLabel->setText("获取文件列表失败");
        ui->connectionInfoTextEdit->append("获取文件列表失败: " + message);
    }
    if (ui->infoTabs->currentIndex() == 0) {
        ui->infoTabs->setCurrentIndex(1);
    }
}

void FtpClientMainWindow::onDownloadProgress(qint64 bytesRead, qint64 totalBytes)
{
    if (totalBytes > 0) {
        int progress = static_cast<int>((bytesRead * 100.0) / totalBytes);
        ui->fileTransferProgressBar->setValue(progress);
    }
}

void FtpClientMainWindow::onDownloadFinished(bool success, const QString &fileName, const QString &message)
{
    ui->fileTransferProgressBar->setVisible(false);
    
    if (success) {
        refreshLocalFileList(ui->localPathLineEdit->text());
        ui->statusInfoLabel->setText("下载完成");
        ui->connectionInfoTextEdit->append("文件下载成功: " + fileName);
        QMessageBox::information(this, "成功", "文件下载成功");
    } else {
        ui->statusInfoLabel->setText("下载失败");
        ui->connectionInfoTextEdit->append("文件下载失败: " + message);
        QMessageBox::warning(this, "失败", "文件下载失败: " + message);
    }
    
}

void FtpClientMainWindow::onUploadProgress(qint64 bytesSent, qint64 totalBytes)
{
    if (totalBytes > 0) {
        int progress = static_cast<int>((bytesSent * 100.0) / totalBytes);
        ui->fileTransferProgressBar->setValue(progress);
    }
}

void FtpClientMainWindow::onUploadFinished(bool success, const QString &fileName, const QString &message)
{
    ui->fileTransferProgressBar->setVisible(false);
    
    if (success) {
        ui->statusInfoLabel->setText("上传完成");
        ui->connectionInfoTextEdit->append("文件上传成功: " + fileName);
        QMessageBox::information(this, "成功", "文件上传成功");
        onListButtonClicked();
    } else {
        ui->statusInfoLabel->setText("上传失败");
        ui->connectionInfoTextEdit->append("文件上传失败: " + message);
        QMessageBox::warning(this, "失败", "文件上传失败: " + message);
    }
}

void FtpClientMainWindow::onDeleteFinished(bool success, const QString &fileName, const QString &message)
{
    if (success) {
        ui->statusInfoLabel->setText("删除完成");
        ui->connectionInfoTextEdit->append("文件删除成功: " + fileName);
        
        // 刷新文件列表
        onListButtonClicked();
    } else {
        ui->statusInfoLabel->setText("删除失败");
        ui->connectionInfoTextEdit->append("文件删除失败: " + message);
        QMessageBox::warning(this, "失败", "文件删除失败: " + message);
    }
}

void FtpClientMainWindow::onFtpError(const QString &message)
{
    ui->statusInfoLabel->setText("发生错误");
    ui->connectionInfoTextEdit->append("错误: " + message);
    QMessageBox::warning(this, "错误", message);
}

void FtpClientMainWindow::onDirectoryChanged(bool success, const QString &directory, const QString &message)
{
    if (success) {
        ui->statusInfoLabel->setText(QString("已切换到目录: %1").arg(directory));
        ui->connectionInfoTextEdit->append(QString("目录切换成功: %1").arg(directory));
        onListButtonClicked();
    } else {
        ui->statusInfoLabel->setText(QString("切换目录失败: %1").arg(message));
        ui->connectionInfoTextEdit->append(QString("目录切换失败: %1 - %2").arg(directory).arg(message));
        QMessageBox::warning(this, "警告", QString("切换目录失败: %1").arg(message));
    }
}

void FtpClientMainWindow::onRemoteFileCellDoubleClicked(int row, int column)
{
    // 获取点击行的类型信息
    QTableWidgetItem *typeItem = ui->remoteFileTableWidget->item(row, 1);
    if (!typeItem || typeItem->text() != "目录") {
        // 如果不是目录，把文件名填到下载文件名LineEdit里
        QTableWidgetItem* nameItem = ui->remoteFileTableWidget->item(row, 0);
        if (!nameItem) {
            return;
        }

        QString fileName = nameItem->text();
        ui->fileNameLineEdit->setText(fileName);
        return;
    }
    
    // 获取目录名
    QTableWidgetItem *nameItem = ui->remoteFileTableWidget->item(row, 0);
    if (!nameItem) {
        return;
    }
    
    QString directoryName = nameItem->text();
    ui->statusInfoLabel->setText(QString("正在切换到目录: %1").arg(directoryName));
    ui->connectionInfoTextEdit->append(QString("尝试切换到目录: %1").arg(directoryName));
    
    // 发送CD命令切换目录
    m_ftpClient->changeDirectory(directoryName);
}

void FtpClientMainWindow::showEvent(QShowEvent* event)
{
    // FTP客户端信号连接
    connect(m_ftpClient, &FtpClient::connected, this, &FtpClientMainWindow::onFtpConnected);
    connect(m_ftpClient, &FtpClient::disconnected, this, &FtpClientMainWindow::onFtpDisconnected);
    connect(m_ftpClient, &FtpClient::fileListReceived, this, &FtpClientMainWindow::onFileListReceived);
    connect(m_ftpClient, &FtpClient::directoryChanged, this, &FtpClientMainWindow::onDirectoryChanged);
    connect(m_ftpClient, &FtpClient::downloadProgress, this, &FtpClientMainWindow::onDownloadProgress);
    connect(m_ftpClient, &FtpClient::downloadFinished, this, &FtpClientMainWindow::onDownloadFinished);
    connect(m_ftpClient, &FtpClient::uploadProgress, this, &FtpClientMainWindow::onUploadProgress);
    connect(m_ftpClient, &FtpClient::uploadFinished, this, &FtpClientMainWindow::onUploadFinished);
    connect(m_ftpClient, &FtpClient::deleteFinished, this, &FtpClientMainWindow::onDeleteFinished);
    connect(m_ftpClient, &FtpClient::error, this, &FtpClientMainWindow::onFtpError);

    QMainWindow::showEvent(event);
}

void FtpClientMainWindow::closeEvent(QCloseEvent* event)
{
    m_ftpClient->disconnect();
    QMainWindow::closeEvent(event);
}

void FtpClientMainWindow::loadSettings(const QString &iniFileName, const QString &groupName)
{
    QSettings settings(iniFileName, QSettings::IniFormat);
    settings.beginGroup(groupName);
    
    // 加载服务器地址、用户名等设置
    ui->serverAddressLineEdit->setText(settings.value("serverAddress").toString());
    ui->usernameLineEdit->setText(settings.value("username").toString());
    ui->passwordLineEdit->setText(settings.value("password").toString());
    m_port = settings.value("port").toUInt();
    m_ftpClient->setUsePasv(settings.value("passiveMode", true).toBool());
    m_ftpClient->setUsePasv2(settings.value("passiveMode2", false).toBool());
    
    // 加载本地路径设置
    ui->localPathLineEdit->setText(settings.value("localPath", QDir::currentPath()).toString());
    refreshLocalFileList(ui->localPathLineEdit->text());
    // 加载窗口位置和大小
    QPoint pos = settings.value("windowPosition", QPoint(0, 0)).toPoint();
    QSize size = settings.value("windowSize", QSize(800, 600)).toSize();
    move(pos);
    resize(size);
    
    // 从配置加载表头宽度比例
    QByteArray headerState = settings.value("headerStateR").toByteArray();
    if (!headerState.isEmpty()) {
        ui->remoteFileTableWidget->horizontalHeader()->restoreState(headerState);
    }

    headerState = settings.value("headerStateL").toByteArray();
    if (!headerState.isEmpty()) {
        ui->localFileTableWidget->horizontalHeader()->restoreState(headerState);
    }

    // 恢复splitter的状态
    if (settings.contains("SplitterSizes")) {
        QStringList sList = settings.value("SplitterSizes").toString().split(",");
        QList<int> sizes;
        for (const auto& i : sList) {
            sizes.push_back(i.toInt());
        }
        if (sizes.size() >= 2) {
            ui->filesSplitter->setSizes(sizes);
        }
        else {
            // 默认分配宽度
            ui->filesSplitter->setSizes(QList<int>() << 400 << 400);
        }
    }
    else {
        // 默认分配宽度
        ui->filesSplitter->setSizes(QList<int>() << 400 << 400);
    }
    
    settings.endGroup();

    m_iniFile = iniFileName;
    m_groupName = groupName;
}

void FtpClientMainWindow::saveSettings(const QString &iniFileName, const QString &groupName)
{
    QSettings settings(iniFileName, QSettings::IniFormat);
    settings.beginGroup(groupName);
    
    // 保存服务器地址、用户名等设置
    settings.setValue("serverAddress", ui->serverAddressLineEdit->text());
    settings.setValue("username", ui->usernameLineEdit->text());
    settings.setValue("password", ui->passwordLineEdit->text());
    
    // 保存本地路径设置
    settings.setValue("localPath", ui->localPathLineEdit->text());
    
    // 保存窗口位置和大小
    settings.setValue("windowPosition", pos());
    settings.setValue("windowSize", size());
    

    settings.setValue("headerStateR", ui->remoteFileTableWidget->horizontalHeader()->saveState());
    settings.setValue("headerStateL", ui->localFileTableWidget->horizontalHeader()->saveState());
#if 1
    // 保存splitter的状态
    QList<int> splitterSizes = ui->filesSplitter->sizes();
    QStringList slist;
    for (auto& i : splitterSizes) {
        slist.push_back(QString::number(i));
    }
    settings.setValue("SplitterSizes", slist.join(","));
#endif

    settings.endGroup();
}


void FtpClientMainWindow::onLocalTableHeaderDoubleClicked(int logicalIndex)
{
    // 切换排序方向
    Qt::SortOrder order = localColOrder[logicalIndex];
    order = (order == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder;
    localColOrder[logicalIndex] = order;
    
    // 禁用自动排序，我们手动处理排序
    ui->localFileTableWidget->setSortingEnabled(false);
    
    if (logicalIndex == 2) { // 如果是大小列
        // 使用我们的自定义排序逻辑
        int rowCount = ui->localFileTableWidget->rowCount();
        QVector<QPair<qint64, int>> sizeRowPairs;
        
        // 收集每行的文件大小和行索引
        for (int row = 0; row < rowCount; ++row) {
            QTableWidgetItem *item = ui->localFileTableWidget->item(row, 0);
            if (!item) continue;
            
            QString fileName = item->text();
            QString fullPath = QDir(m_currentLocalPath).absoluteFilePath(fileName);
            QFileInfo fileInfo(fullPath);
            qint64 size = fileInfo.exists() ? fileInfo.size() : 0;
            
            sizeRowPairs.append({size, row});
        }
        
        // 根据文件大小排序
        if (order == Qt::AscendingOrder) {
            std::sort(sizeRowPairs.begin(), sizeRowPairs.end(), 
                      [](const QPair<qint64, int>& a, const QPair<qint64, int>& b) {
                          return a.first < b.first;
                      });
        } else {
            std::sort(sizeRowPairs.begin(), sizeRowPairs.end(), 
                      [](const QPair<qint64, int>& a, const QPair<qint64, int>& b) {
                          return a.first > b.first;
                      });
        }
        
        // 创建新的排序后的行数据
        QList<QList<QTableWidgetItem*>> sortedRows;
        for (const auto& pair : sizeRowPairs) {
            QList<QTableWidgetItem*> rowItems;
            for (int col = 0; col < FILE_LIST_COLUMNS; ++col) {
                QTableWidgetItem *item = ui->localFileTableWidget->item(pair.second, col);
                if (item) {
                    rowItems.append(new QTableWidgetItem(*item));
                } else {
                    rowItems.append(new QTableWidgetItem(""));
                }
            }
            sortedRows.append(rowItems);
        }
        
        // 清空表格并重新填充排序后的数据
        ui->localFileTableWidget->clearContents();
        ui->localFileTableWidget->setRowCount(sortedRows.size());
        
        int row = 0;
        for (const auto& rowItems : sortedRows) {
            for (int col = 0; col < rowItems.size(); ++col) {
                ui->localFileTableWidget->setItem(row, col, rowItems[col]);
            }
            ++row;
        }
    } else {
        // 其他列使用默认排序
        ui->localFileTableWidget->setSortingEnabled(true);
        ui->localFileTableWidget->sortByColumn(logicalIndex, order);
        ui->localFileTableWidget->setSortingEnabled(false);
    }
    
    // 设置排序指示器
    ui->localFileTableWidget->horizontalHeader()->setSortIndicator(logicalIndex, order);
}

void FtpClientMainWindow::onRemoteTableHeaderDoubleClicked(int logicalIndex)
{
    // 切换排序方向
    Qt::SortOrder order = remoteColOrder[logicalIndex];
    order = (order == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder;
    remoteColOrder[logicalIndex] = order;
    
    // 禁用自动排序，我们手动处理排序
    ui->remoteFileTableWidget->setSortingEnabled(false);
    
    if (logicalIndex == 2) { // 如果是大小列
        // 使用我们的自定义排序逻辑
        int rowCount = ui->remoteFileTableWidget->rowCount();
        QVector<QPair<qint64, int>> sizeRowPairs;
        
        // 收集每行的文件大小和行索引
        for (int row = 0; row < rowCount; ++row) {
            QTableWidgetItem *item = ui->remoteFileTableWidget->item(row, 0);
            if (!item) continue;
            
            QString fileName = item->text();
            qint64 size = m_fileSizeMap.contains(fileName) ? m_fileSizeMap.value(fileName) : 0;
            
            sizeRowPairs.append({size, row});
        }
        
        // 根据文件大小排序
        if (order == Qt::AscendingOrder) {
            std::sort(sizeRowPairs.begin(), sizeRowPairs.end(), 
                      [](const QPair<qint64, int>& a, const QPair<qint64, int>& b) {
                          return a.first < b.first;
                      });
        } else {
            std::sort(sizeRowPairs.begin(), sizeRowPairs.end(), 
                      [](const QPair<qint64, int>& a, const QPair<qint64, int>& b) {
                          return a.first > b.first;
                      });
        }
        
        // 创建新的排序后的行数据
        QList<QList<QTableWidgetItem*>> sortedRows;
        for (const auto& pair : sizeRowPairs) {
            QList<QTableWidgetItem*> rowItems;
            for (int col = 0; col < FILE_LIST_COLUMNS; ++col) {
                QTableWidgetItem *item = ui->remoteFileTableWidget->item(pair.second, col);
                if (item) {
                    rowItems.append(new QTableWidgetItem(*item));
                } else {
                    rowItems.append(new QTableWidgetItem(""));
                }
            }
            sortedRows.append(rowItems);
        }
        
        // 清空表格并重新填充排序后的数据
        ui->remoteFileTableWidget->clearContents();
        ui->remoteFileTableWidget->setRowCount(sortedRows.size());
        
        int row = 0;
        for (const auto& rowItems : sortedRows) {
            for (int col = 0; col < rowItems.size(); ++col) {
                ui->remoteFileTableWidget->setItem(row, col, rowItems[col]);
            }
            ++row;
        }
    } else {
        // 其他列使用默认排序
        ui->remoteFileTableWidget->setSortingEnabled(true);
        ui->remoteFileTableWidget->sortByColumn(logicalIndex, order);
        ui->remoteFileTableWidget->setSortingEnabled(false);
    }
    
    // 设置排序指示器
    ui->remoteFileTableWidget->horizontalHeader()->setSortIndicator(logicalIndex, order);
}